<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <view class="Mall4j page-specification-management">
    <view
      v-if="specList.length > 0"
      class="spec"
    >
      <view
        v-for="(item, index) in specList"
        :key="index"
      >
        <!-- 有图的规格 -->
        <view
          v-if="index === 0"
          class="spec-item"
        >
          <view class="spec-name">
            <view>{{ item.name }}</view>
            <view
              class="edit-icon-box"
              @tap="showEdit = true;showIndex=index"
            >
              <view
                v-for="dot in 3"
                :key="dot"
                class="edit-icon"
              />
            </view>
          </view>
          <view
            v-if="showEdit && showIndex === index"
            class="popup"
          >
            <view
              class="mask-edit"
              @tap="mask"
            />
            <view class="edit-popup">
              <view
                class="item"
                @tap.stop="edit(1, item.name, index)"
              >
                编辑规格名
              </view>
              <view
                class="item"
                @tap.stop="edit(2, item, index)"
              >
                编辑规格值
              </view>
              <view
                class="item"
                @tap.stop="deletespec(item.name, index)"
              >
                删除
              </view>
            </view>
          </view>
          <view
            v-if="item.prodPropValues.length === 0"
            class="empty-spec-vaule"
            @tap="addApec(item.propId,index)"
          >
            <view class="empty-spec-vaule-item">
              <view class="add-icon">
                +
              </view>
              添加规格值
            </view>
          </view>
          <view v-if="item.prodPropValues.length > 0">
            <view class="spec-vaule">
              <view
                v-for="(itemValue, indexValue) in item.prodPropValues"
                :key="indexValue"
                :class="[isUpImg ? 'spec-vaule-item-img' : 'spec-vaule-item']"
              >
                <img-upload
                  v-if="isUpImg"
                  :pic="itemValue.pic"
                  :img-id="indexValue"
                  @delete-img="deleteImg"
                  @up-load-img="uploadImg"
                />
                <view class="vaule">
                  {{ itemValue.propValue }}
                </view>
              </view>
            </view>
            <view class="line" />
            <view class="spec-value-image-switch">
              <view class="title">
                <view class="big-text">
                  添加规格图片
                </view>
                <view class="explanation-text">
                  （仅第一组规格值可添加）
                </view>
              </view>
              <switch
                ref="isUpImgRef"
                :checked="isUpImg"
                style="transform:scale(0.75);"
                color="#082BA6"
                @change="switchChange"
              />
            </view>
          </view>
        </view>
        <!-- 有图的规格 -->

        <!-- 无图的规格 -->
        <view
          v-if="index > 0"
          class="spec-item"
        >
          <view class="spec-name">
            <view class="text">
              {{ item.name }}
            </view>
            <view
              class="edit-icon-box"
              @tap="showEdit = true;showIndex=index"
            >
              <view
                v-for="dot in 3"
                :key="dot"
                class="edit-icon"
              />
            </view>
          </view>
          <view
            v-if="showEdit && showIndex === index"
            class="popup"
          >
            <view
              class="mask-edit"
              @tap="mask"
            />
            <view class="edit-popup">
              <view
                class="item"
                @tap.stop="edit(1, item.name, index)"
              >
                编辑规格名
              </view>
              <view
                class="item"
                @tap.stop="edit(2, item, index)"
              >
                编辑规格值
              </view>
              <view
                class="item"
                @tap.stop="deletespec(item.name, index)"
              >
                删除
              </view>
            </view>
          </view>
          <view
            v-if="item.prodPropValues.length === 0"
            class="empty-spec-vaule"
            @tap="addApec(item.propId,index)"
          >
            <view class="empty-spec-vaule-item">
              <view class="add-icon">
                +
              </view>
              添加规格值
            </view>
          </view>
          <view class="spec-vaule">
            <view
              v-for="(itemValue, indexValue) in item.prodPropValues"
              :key="indexValue"
              class="spec-vaule-item"
            >
              <view class="vaule">
                {{ itemValue.propValue }}
              </view>
            </view>
          </view>
        </view>
      <!-- 无图的规格 -->
      </view>
    </view>
    <empty-tips
      v-else
      :tips-list="tipsList"
    />
    <view class="specification-management-footer">
      <common-btn
        :btn-config="prodManaBtnConfig"
        @handle-click-btn="AddSku"
        @handle-click-more-btn="handleClickMoreBtn"
      />
    </view>
    <add-specification-name
      v-if="showAddSpecificationName"
      :add-title="addTitle"
      :data-list="specComList"
      :all-data="specAllNameList"
      :spec-name="specName"
      @cancal="closeAddSpecificationName"
      @search="search"
    />

    <create-popup
      v-if="showCreatePopup"
      :reg-tip="regTip"
      :input-val="createSkuName"
      :is-required="true"
      :config="createConfig"
      @cancal="closeCreatePopup"
      @submit="getSubmitData"
    />
  </view>
</template>

<script setup>
import createPopup from '@/package-prod/components/create-popup/create-popup.vue'
import AddSpecificationName from '@/package-prod/components/add-specification-name/add-specification-name.vue'

const prodStore = useProdStore()

const tipsList = ['您还没有添加规格', '仅支持为第一组规格设置规格值图片']

const Data = reactive({
  prodManaBtnConfig: {
    btnText: '添加规格',
    isPlain: false
  },
  regTip: {
    reg: /^.*[:|;|：|；].*$/,
    regTip: '请勿输入符号“;”和“:”'
  },
  createSkuName: '', // 新增规格名
  // 新增规格tip
  createConfig: {
    header: '编辑规格名',
    placeholder: '请输入规格名',
    cancalText: '取消',
    submitText: '确定',
    submitTip: '请输入规格名',
    maxlength: 10
  },
  showCreatePopup: false, // 显示新增/修改弹窗
  showEdit: false, // 右侧操作栏显示
  showIndex: -1, // 右侧操作栏index
  showAddSpecificationName: false, // 规格值/名编辑层显示
  isUpImg: true, // 是否上传图片
  specList: [], // 规格数据
  dataList: [], // 搜索原始名/值数据
  specComList: [], // 搜索显示名/值数据
  specAllNameList: [], // 已选规格名列表
  specAllData: {}, // 所有查询返回sku数据
  editIndex: '', // 修改index
  addTitle: 'name', // 当前新增类型（name, value）

  specData: [] // 原数据
})

const { prodManaBtnConfig, regTip, createSkuName, createConfig, showCreatePopup, showEdit, showIndex, showAddSpecificationName, isUpImg, specList, specComList, specAllNameList, addTitle } = toRefs(Data)

const specName = computed(() => {
  return Array.from(new Set([...Data.specList.map(x => x.name), ...Data.dataList.map(x => x.name)]))
})

/**
* 生命周期函数--监听页面显示
*/
onShow(() => {
  // 加载导航标题
  uni.setNavigationBarTitle({
    title: '商品规格'
  })
})

onMounted(() => {
  Data.specData = prodStore.dataForm.skuList
  Data.specData.forEach(x => {
    x.changeStock = parseInt(x.stocks)
  })
  if (prodStore.dataForm.isUpImg) {
    Data.isUpImg = prodStore.dataForm.isUpImg
  }
  dealSpecData()
  getSpecData()
})

// 处理反显数据
const dealSpecData = () => {
  if (Data.specData.length > 0) {
    const data = Data.specData
    if (data[0].properties === '') {
      return
    }
    const valueObj = {}
    const skuList = {}
    const nameList = data[0].properties.split(';').map((item) => {
      const name = item.slice(0, item.indexOf(':'))
      valueObj[name] = []
      skuList[name] = []
      return name
    })
    data.forEach((item) => {
      const list = item.properties.split(';')
      for (let i = 0; i < nameList.length; i++) {
        const index = list[i].indexOf(':')
        const sku = [list[i].slice(0, index), list[i].substring(index + 1)]
        if (skuList[nameList[i]].indexOf(sku[1]) < 0) {
          skuList[nameList[i]].push(sku[1])
          valueObj[sku[0]].push({
            isSelect: true,
            name: sku[1],
            pic: (i === 0 ? item.pic : ''),
            propId: item.prodId,
            propValue: sku[1],
            propValueEn: sku[1],
            valueId: ''
          })
        }
      }
    })
    nameList.forEach((item) => {
      Data.specList.push({
        name: item,
        prodPropValues: valueObj[item]
      })
    })
    isShowBreak()
  }
}

// 获取规格数据
const getSpecData = () => {
  http.request({
    url: '/prod/spec/list',
    method: 'GET',
    data: {}
  }).then(({ data: res }) => {
    res.forEach(item => {
      Data.specAllData[item.propId] = item.prodPropValues
      item.prodPropValues = []
    })
    Data.dataList = dealList(res)
    if (Data.addTitle === 'name') {
      Data.specAllNameList = Data.dataList.map((item) => {
        return item.name
      })
      Data.specComList = Data.dataList
      if (Data.specData.length > 0) {
        const nameList = Data.specList.map((item) => {
          return item.name
        })
        const list = []
        Data.specComList.forEach((item) => {
          if (nameList.indexOf(item.name) < 0) {
            list.push(item)
          } else {
            Data.specList[nameList.indexOf(item.name)].propId = item.propId
          }
        })
        Data.specComList = list
        Data.dataList = list
      }
    }
  })
}

// 底部按钮点击
const handleClickMoreBtn = (index) => {
  switch (index) {
    case 1:
      AddSku()
      break
    case 2:
      toBreakDown()
      break
    case 3:
      handleSubmit()
      break
  }
}

// 规格明细
const toBreakDown = () => {
  handleSubmit(true)
}

const deleteImg = (index) => {
  const data = Data.specList[0].prodPropValues[index]
  data.pic = ''
  Data.specList[0].prodPropValues.index = data
}

// 拼接保存数据
const dealSpecList = (specListData = [], isReverse = false) => {
  const specList = JSON.parse(JSON.stringify(specListData))
  if (specList.length === 0) return []
  if (isReverse) specList.reverse()
  const imgIndex = isReverse ? specList.length - 1 : 0
  const onevalueList = specList[imgIndex].prodPropValues.map((item) => {
    return item.name
  })
  const valuesList = specList.map((item) => {
    return item.prodPropValues
  })
  const specTeams = specTeam(valuesList)
  const dataForm = []
  specTeams.forEach((item) => {
    let properties = ''
    item.forEach((itemName, index) => {
      properties += specList[specList.length - 1 - index].name + ':' + itemName + (index !== (item.length - 1) ? ';' : '')
    })
    let pic = ''
    pic = onevalueList.indexOf(item[0]) > -1 ? specList[imgIndex].prodPropValues[onevalueList.indexOf(item[0])].pic : ''
    pic = pic || ''
    dataForm.push({
      name: item,
      changeStock: null,
      price: 0.01,
      stocks: 0,
      pic,
      oriPrice: 0.01,
      volume: 0,
      weight: 0,
      status: 1,
      partyCode: '',
      prodName: prodStore.dataForm.prodName + ' ' + item.join(' '),
      properties,
      skuName: item.join(' '),
      isShow: true,
      isSelect: false
    })
  })
  return dataForm
}

// 组合规格值（笛卡儿积）
const specTeam = (arr) => {
  let specTeams = []
  for (let i = 0; i < arr.length; i++) {
    const test = []
    for (let x = 0; x < arr[i].length; x++) {
      if (i === 0) {
        test[x] = [arr[i][x].name]
      } else {
        for (let y = 0; y < specTeams.length; y++) {
          test[test.length] = [arr[i][x].name]
          specTeams[y].forEach((item) => {
            test[test.length - 1].push(item)
          })
        }
      }
    }
    specTeams = test
  }
  return specTeams
}

// 点击新增规格
const AddSku = () => {
  if (Data.specList.length > 0 && Data.specList[Data.specList.length - 1].prodPropValues.length === 0) {
    uni.showToast({
      title: '请先完善已添加规格',
      mask: true,
      icon: 'none',
      duration: 1500
    })
    return
  }
  if (Data.specList.length >= 3) {
    uni.showToast({
      title: '最多可添加3个规格',
      mask: true,
      icon: 'none',
      duration: 1500
    })
    return
  }
  Data.addTitle = 'name'
  Data.specComList = Data.dataList
  Data.showAddSpecificationName = true
}

// 保存
const handleSubmit = (index = false) => {
  let specListValue = dealSpecList(Data.specList, true)

  // 判断是否编辑原数据
  if (Data.specData.length > 0) {
    const propertiesList = Data.specData.map((item) => {
      return item.properties
    })
    let num = 0
    specListValue.forEach((item) => {
      const index = propertiesList.indexOf(item.properties)
      if (index > -1) {
        num++
        if (Data.specData[index].pic !== item.pic) {
          Data.specData[index].pic = item.pic
        }
      }
    })
    if (num === specListValue.length && num === Data.specData.length) {
      specListValue = Data.specData
      specListValue.forEach((item) => {
        item.changeStock = 0
      })
    }
  }
  prodStore.dataForm.skuList = specListValue
  if (index) {
    uni.navigateTo({
      url: '/package-prod/pages/specification-breakdown/specification-breakdown'
    })
  } else {
    uni.navigateTo({
      url: '/package-prod/pages/post-prod/post-prod'
    })
  }
}

// 规格搜索
const search = (val) => {
  if (!val) {
    Data.specComList = Data.dataList
    return
  }
  const list = []
  Data.dataList.forEach((item) => {
    if (item.name.indexOf(val) > -1) {
      list.push(item)
    }
  })
  Data.specComList = list
}

// 屏蔽层点击
const mask = () => {
  Data.showEdit = false
}

// 点击添加规格值
const addApec = (id, index) => {
  Data.addTitle = 'value'
  Data.specComList = []
  Data.editIndex = index
  // 判断数据是否存在该规格
  if (!id) {
    const tag = Data.dataList.find(el => el.name === Data.specList[index].name)
    id = tag ? tag.id : ''
  }
  if (!id) {
    Data.showAddSpecificationName = true
    return
  }
  getSpecValues(id, 2)
}

// 根据规格id获取规格（type: 1规格名; 2规格值）
const getSpecValues = (id, type, prodPropValues = []) => {
  if (Object.keys(Data.specAllData).length > 0) {
    getSpecValuesDeal(Data.specAllData[id], type, prodPropValues)
  } else {
    http.request({
      url: '/prod/spec/listSpecValue/' + id,
      method: 'GET'
    }).then(({ data }) => {
      getSpecValuesDeal(data, type, prodPropValues)
    })
  }
}

// 获取规格值处理
const getSpecValuesDeal = (res, type, prodPropValues) => {
  const valueList = res.length > 0 ? res : []
  if (type === 1) {
    valueList.forEach((item) => {
      item.isSelect = false
      item.name = item.propValue
    })
  } else {
    const valuseName = prodPropValues.map((vitem) => {
      return vitem.name
    })
    // 规格值数据
    valueList.forEach((item) => {
      item.name = item.propValue
      item.isSelect = false
      item.pic = ''
      if (valuseName.indexOf(item.name) > -1) {
        prodPropValues[valuseName.indexOf(item.name)].isSelect = true
        // item.isSelect = true
        // item.pic = prodPropValues[valuseName.indexOf(item.name)].pic
      } else {
        prodPropValues.push(item)
      }
    })
    if (valuseName.length === 0) {
      prodPropValues = valueList
    }
  }
  Data.specComList = prodPropValues
  Data.showAddSpecificationName = true
}

// 处理规格名数据
const dealList = (list) => {
  list.forEach((item) => {
    item.name = item.propName
    item.id = item.propId
    item.prodPropValues = item.prodPropValues ? item.prodPropValues : []
  })
  return list
}

// 编辑规格名/值（type: 1规格名; 2规格值）
const edit = (type, v, index) => {
  Data.editIndex = index
  if (type === 1) {
    mask()
    Data.showCreatePopup = true
    Data.createSkuName = v.toString()
  }
  if (type === 2) {
    mask()
    Data.addTitle = 'value'
    const list = JSON.parse(JSON.stringify(Data.specList[index].prodPropValues))
    if (!v.propId) {
      Data.specComList = Data.specList[index].prodPropValues
      Data.showAddSpecificationName = true
      return
    }
    getSpecValues(v.propId, 2, list)
  }
}

// 删除指定规格
const deletespec = (name, index) => {
  mask()
  uni.showModal({
    title: '',
    content: '确定删除“' + name + '”规格',
    cancelText: '取消',
    confirmText: '删除',
    confirmColor: '#082BA6',
    success (res) {
      if (res.confirm) {
        // 删除的规格名加入可选队列
        if (Data.specList[index].propId) {
          Data.dataList.push(Data.specList[index])
        }
        Data.specList[index].prodPropValues = []
        Data.specList.splice(index, 1)
        Data.specAllNameList = Data.specList.map((item) => {
          return item.name
        })
        isShowBreak()
        prodStore.dataForm.skuList = dealSpecList(Data.specList)
      }
    }
  })
}

// 添加规格名/值回调
const closeAddSpecificationName = (item) => {
  Data.showAddSpecificationName = false
  if (item === '') {
    return
  }
  if (Data.addTitle === 'value') {
    Data.specComList = []
    Data.specList[Data.editIndex].prodPropValues = item
    Data.editIndex = ''
  } else {
    if (Data.specComList.indexOf(item) > -1) {
      Data.specComList = Data.dataList
      Data.specComList.splice(Data.specComList.indexOf(item), 1)
      Data.dataList = Data.specComList
    }
    Data.specList.push(item)
    Data.specAllNameList = Data.specList.map((item) => {
      return item.name
    })
  }
  isShowBreak()
}

// 动态修改下方按钮
const isShowBreak = () => {
  if (Data.specList.length > 0 && Data.specList[Data.specList.length - 1].prodPropValues.length > 0) {
    Data.prodManaBtnConfig = {
      btnList: [
        {
          btnText: '添加规格',
          isPlain: true
        },
        {
          btnText: '添加规格明细',
          isPlain: true
        },
        {
          btnText: '保存',
          isPlain: false
        }
      ]
    }
  } else {
    Data.prodManaBtnConfig = {
      btnText: '添加规格',
      isPlain: false

    }
  }
}

// 上传图片
const uploadImg = (val) => {
  http.request({
    url: '/admin/file/attachFilePage',
    method: 'get',
    data: {
      fileId: val.value,
      current: 1,
      size: 1,
      type: 1
    }
  }).then(({ data }) => {
    uni.hideLoading()
    const pic = data.records[0].filePath
    const prodPropValues = Data.specList[0]
    prodPropValues.prodPropValues[val.id].pic = pic
    Data.specList[0] = prodPropValues
  })
}

// 关闭编辑规格名
const closeCreatePopup = () => {
  Data.showCreatePopup = false
}

// 编辑规格名
const getSubmitData = (res) => {
  if (Data.specName.indexOf(res) > -1) {
    uni.showToast({
      title: `规格名'${res}'已存在`,
      mask: true,
      icon: 'none',
      duration: 1500
    })
    return
  }
  Data.showCreatePopup = false
  Data.specList[Data.editIndex].name = res
  Data.editIndex = ''
}

// 是否添加图片
const switchChange = () => {
  Data.isUpImg = !Data.isUpImg
  prodStore.dataForm.isUpImg = Data.isUpImg
  Data.specList[0].prodPropValues.forEach((item) => {
    item.pic = ''
  })
}
</script>

<style lang="scss" scoped>
@use "specification-management.scss";
</style>
